<?php

namespace app\api\controller;

use app\common\controller\Api;
use addons\litestore\model\Litestorenews;
use app\admin\model\LitestoreRequest;
use app\admin\model\LitestoreServiceOrderType;
use app\admin\model\LitestoreCardTpl;
use think\Db;
use EasyWeChat\Foundation\Application;
use addons\litestore\library\Service;
use addons\third\model\Third;
use app\common\library\Auth;
use fast\Http;
use fast\Random;

use think\Config;
use think\Validate;
use think\Log;

use function Complex\sec;

/**
 * 机制炭的小程序接口
 * 变更版本 变更日期 变更内容                                 变更人
 * v1.0    20200912 初稿                                    宋蔚财
 * v1.1    20200912 初稿                                    宋蔚财
 * v1.2    20200913 初稿                                    宋蔚财
 * v1.3    20200913 初稿                                    宋蔚财
 * v1.4    20200913 初稿                                    宋蔚财
 * v1.5    20200917 初稿                                    宋蔚财 
 * v1.6    20200917 初稿                                    宋蔚财 
 * v1.6    20200917 增加认证类型接口                         宋蔚财 
 */
class Jzt extends Api
{
    //protected $noNeedLogin = ['login_hawk','Updata_user_hawk'];
    protected $noNeedLogin = ['*'];

    public function _initialize()
    {
        $this->token = $this->request->post('token');
        if ($this->request->action() == 'login' && $this->token) {
            $this->request->post(['token' => '']);
        }
        parent::_initialize();
    }

    private function startsWith($str, $prefix)
    {
        for ($i = 0; $i < strlen($prefix); ++$i) {
            if ($prefix[$i] !== $str[$i]) {
                return false;
            }
        }
        return true;
    }

    private function format_cdnurl($image_url){
        if(empty($image_url))
        {
            return "";
        }
        if($this->startsWith($image_url,"/uploads/")){
            return cdnurl($image_url, true);
        }
        else{
            return $image_url;
        }
        
    }
    
    private function Format_avatarUrl($userInfo){
        $avatar = $userInfo['avatar'];
        if($this->startsWith($avatar,"/uploads/")){
            $userInfo['avatar'] = cdnurl($avatar, true);
        }
        return ['userInfo' => $userInfo];
    }

    /**
     * 获取主页的banner 图标列表
     * @param  void
     * @return bannerlist
     */
    public function bannerlist()
    {
        Log::info("***********************************************************************bannerlist start*******************************************************");
        
        $banner     = new Litestorenews();
        $bannerdata = $banner->where('status', 'normal')->order('updatetime', 'desc')->limit(6)->select();

        foreach ($bannerdata as $index => $item) {;
            $bannerdata[$index] = ['image' => cdnurl($item['image'], true),'id'=> $item['content']];
        }
        Log::info($bannerdata);
        Log::info("***********************************************************************bannerlist end*******************************************************");
        $this->success('获取成功', [
                        'bannerlist' => $bannerdata
      ]);
    }

     /**
     * 获取主页的供求信息随机列表 
     * 
     */
    public function reqlist()
    {
        Log::info("***********************************************************************reqlist start*******************************************************");
        $banner     = new LitestoreRequest();
        $bannerdata =  $banner->Order('updatetime desc')->limit(10)->select();
        $bannerList = [];

        foreach ($bannerdata as $index => $item) {
            $bannerList[] = [
            'id'=> $item['id'],
            'title'=> $item['title'],
            'brand'=> $item['brand'],
            'specs'=> $item['specs'],            
            'num'=> $item['num'],            
            'type'=> $item['type'],
            'price'=> $item['price'],
            'trans_addr'=> $item['trans_addr'],
            'req_contents'=> $item['req_contents'],
            'publish_time'=> date("Y-m-d",$item['publish_time'])
            ];
        }
        Log::info($bannerList);
        Log::info("***********************************************************************reqlist end*******************************************************");
        $this->success('获取成功', [
                        'reqlist' => $bannerList
      ]);
    }
    /**
     * 获取供求信息列表 
     * 
     * @param 
     */
    public function myreqlist()
    {
        Log::info("***********************************************************************myreqlist start*******************************************************");
        $user_id        = $this->request->post("user_id");
        $page           = empty( $this->request->post("currpage")) ? 1 :  $this->request->post("currpage");//获取当前页数
        $type           = $this->request->post("type");
        $info_type      = $this->request->post("info_type");
        $req_contents   = empty( $this->request->post("req_contents")) ? '' :  $this->request->post("req_contents");//供求内容

        Log::info("param info *****************************************");
        Log::info("user_id=".$user_id);
        Log::info("page=".$page);
        Log::info("type=".$type);
        Log::info("info_type=".$info_type);
        Log::info("req_contents=".$req_contents);
        Log::info("param info *****************************************");

        $where =[];
        if( !empty($user_id)){
        $where['user_id'] =  $user_id;
        }
        Log::info($page);

        if( !empty($content)){
            $where['req_contents'] =  array('like','%'.$req_contents.'%');
        }
        if( !empty($type)){
            $where['type'] =   $type;
        }
        if( !empty($info_type)){
            $where['info_type'] =   $info_type;
        }
       
        
        
        $field ='a.id,a.title,a.user_id,b.avatar,b.nickname,b.mobile,a.brand,a.num,a.specs,a.type,a.price,a.trans_addr,a.req_contents,a.publish_time';
        $requestlist = Db::name('litestore_request')->alias('a')->join('user b','b.id=a.user_id','left')->Order('a.updatetime desc')->field($field)->where($where)->page($page,10)->select();
        $count = Db::name('litestore_request')->alias('a')->join('user b','b.id=a.user_id','left')->where($where)->count();//有多少条数据
        $tatal = ceil($count/10);//要分多少页
        
        foreach ($requestlist as $index => $item) {
            $requestlist[ $index] = [
                'id'=> $item['id'],
                'title'=> $item['title'],
                'user_id'=> $item['user_id'],
                'avatar'=> cdnurl(empty($item['avatar'])?'/uploads/20200823/ph.png':$item['avatar'],true),
                'nickname'=> $item['nickname'],
                'mobile'=> $item['mobile'],
                'num'=> $item['num'],
                'brand'=> $item['brand'],
                'specs'=> $item['specs'],            
                'type'=> $item['type'],
                'price'=> $item['price'],
                'trans_addr'=> $item['trans_addr'],
                'req_contents'=> $item['req_contents'],
                'publish_time'=> date('Y-m-d',$item['publish_time'])
             ];
        }
        Log::info("result info **************************************");
        Log::info($requestlist);
        Log::info("result info **************************************");

        Log::info("***********************************************************************myreqlist end*******************************************************");
        $this->success('获取成功', [
                        'reqlist'=>$requestlist,
                        'tatal'=>$tatal,
                        'currpage'=>$page
                        ]);
    }


     /**
     * 获取供求信息详情
     * 
     * @param 
     */
    public function reqdetail()
    {
        Log::info("***********************************************************************reqdetail start*******************************************************");
        $req_id   = empty( $this->request->post("req_id")) ? '' :  $this->request->post("req_id");//供求信息ID

        if(empty($req_id))
        {
            $this->error(__('供求信息ID不能为空'));
        }
        Log::info("param info *****************************************");
        Log::info("req_id=".$req_id);
        Log::info("param info *****************************************");

        $where =[];
        if( !empty($req_id)){
        $where['id'] =  $req_id;
        }
        
        $reqdetail = Db::query("select a.id,a.user_id,b.mobile,a.num,b.nickname,a.info_type,a.detail_images,b.avatar,a.title,a.brand,a.specs,a.type,a.price,a.trans_addr,req_contents,FROM_UNIXTIME(a.publish_time, '%Y-%m-%d') as publish_time from fa_litestore_request a ,fa_user b where a.id=:req_id and a.user_id = b.id limit 1 ",['req_id'=>$req_id]);
        if(empty($reqdetail))
        {
            $this->error(__('供求信息ID在数据库中未找到记录'));
        }
        $iarr = $reqdetail[0]['detail_images'] ;
        if(!empty($iarr)){
            $images=explode(',',$iarr);
            $num = count($images);
            for($i=0;$i<$num;$i++){
                $images[$i]=empty($images[$i])?"":cdnurl($images[$i],true);
            }
            $reqdetail[0]['detail_images'] = $images;
        }else {
            $reqdetail[0]['detail_images'] = [];
        }
        if(empty($reqdetail[0]['avatar'])){$reqdetail[0]['avatar']='/uploads/20200823/ph.png';}
        
        Log::info("result info *****************************************");
        Log::info($reqdetail[0]);
        Log::info("result info *****************************************");



        Log::info("***********************************************************************reqdetail end*******************************************************");
        
        $this->success('获取成功', [
                        'reqdetail'=>$reqdetail[0],
                        ]);
    }

    

   
    
    /**
     * 增加技术问题
     * @param title  标题
     * @param brand  品牌
     * @param specs  规格
     * @param type   类型
     * @param price  价格
     * @param trans_addr 交货地点
     * @param user_id 用户ID
     * @param req_contents 供求详情
     */
    public function addtechquestion()
    {
        Log::info("***********************************************************************addtechquestion start*******************************************************");
        $user_id   = $this->request->post("user_id");              //用户ID
        $qs_type        = $this->request->post("qs_type");         //问题类型:0=维修问题,1=生产问题,2=原材料问题,3=其他问题  
        $qs_images        = empty($this->request->post("qs_images"))?'':$this->request->post("qs_images");     //问题图片
        $qs_contents        = $this->request->post("qs_contents");  //问题描述

        Log::info("param info *****************************************");
        Log::info("user_id=".$user_id);
        Log::info("qs_type=".$qs_type);
        Log::info("qs_images=".$qs_images);
        Log::info("qs_contents=".$qs_contents);
        Log::info("param info *****************************************");

        if(empty($user_id))
        {
            $this->error(__('用户ID不能为空'));
        }
        if(empty($qs_type))
        {
            $this->error(__('问题类型不能为空'));
        }
        if(empty($qs_contents))
        {
            $this->error(__('问题描述不能为空'));
        }

          $data = ['as_num' => 0, 
                 'qs_status' => 0,
                 'qs_type' =>  $qs_type,
                 'qs_contents' => $qs_contents,
                 'qs_images' =>$qs_images,
                 'createtime' => time(),
                 'updatetime' => time(),
                 'user_id' => $user_id
                ];
        $id= Db::name('litestore_tech_question')->insertGetId($data);
        Log::info("***********************************************************************addtechquestion end*******************************************************");
        $this->success('插入成功', ['id'=>$id]);
    }

    /**
     * 删除技术问题
     * @param title  标题
     * @param brand  品牌
     * @param specs  规格
     * @param type   类型
     * @param price  价格
     * @param trans_addr 交货地点
     * @param user_id 用户ID
     * @param req_contents 供求详情
     */
    public function deletetechquestion()
    {
        Log::info("***********************************************************************addtechquestion start*******************************************************");
        $user_id   = $this->request->post("user_id");              //用户ID
        $id        = $this->request->post("id");         //问题类型:0=维修问题,1=生产问题,2=原材料问题,3=其他问题  
        

        Log::info("param info *****************************************");
        Log::info("user_id=".$user_id);
        Log::info("id=".$id);
        
        Log::info("param info *****************************************");

        if(empty($user_id))
        {
            $this->error(__('用户ID不能为空'));
        }
        if(empty($id))
        {
            $this->error(__('技术问题ID不能为空'));
        }

        Db::table('litestore_tech_question')->where('id', $id)->delete();

        Log::info("***********************************************************************addtechquestion end*******************************************************");
        $this->success('插入成功', ['id'=>$id]);
    }

    /**
     * 增加供求信息
     * @param title  标题
     * @param brand  品牌
     * @param specs  规格
     * @param type   类型
     * @param price  价格
     * @param trans_addr 交货地点
     * @param user_id 用户ID
     * @param req_contents 供求详情
     */
    public function addreq()
    {
        Log::info("***********************************************************************addreq start*******************************************************");          
        $title        =  empty($this->request->post("title"))?'':$this->request->post("title");
        $brand        = empty($this->request->post("brand"))?'电议':$this->request->post("brand");
        $specs        = empty($this->request->post("specs"))?'电议':$this->request->post("specs");
        $type         = empty($this->request->post("type"))?'':$this->request->post("type");
        $price        = empty($this->request->post("price"))?'电议':$this->request->post("price");
        $trans_addr   = empty($this->request->post("trans_addr"))?'':$this->request->post("trans_addr");
        $user_id   = empty($this->request->post("user_id"))?'':$this->request->post("user_id");
        $req_contents = empty($this->request->post("req_contents"))?'':$this->request->post("req_contents");
        $info_type = empty($this->request->post("info_type"))?'':$this->request->post("info_type");
        $detail_images = empty($this->request->post("detail_images"))?'':$this->request->post("detail_images");
        $num        = empty($this->request->post("num"))?'电议':$this->request->post("num");

        Log::info("param info *****************************************");
        Log::info("title=".$title);
        Log::info("brand=".$brand);
        Log::info("specs=".$specs);
        Log::info("type=".$type);
        Log::info("price=".$price);
        Log::info("trans_addr=".$trans_addr);
        Log::info("user_id=".$user_id);
        Log::info("req_contents=".$req_contents);        
        Log::info("info_type=".$info_type);        
        Log::info("detail_images=".$detail_images);        
        Log::info("num=".$num);        
        Log::info("param info *****************************************");

        if(empty($title))
        {
            $this->error(__('供求标题不能为空'));
        }
        if(empty($type))
        {
            $this->error(__('类型不能为空'));
        }

        if(strcmp($type,'1')<>0 && strcmp($type,'2') <>0)
        {
            $this->error(__('类型必须为1,或者2'));
        }
        if(empty($trans_addr))
        {
            $this->error(__('交货地点不能为空'));
        }

        if(empty($req_contents))
        {
            $this->error(__('供求详情不能为空'));
        }
        if(empty($user_id))
        {
            $this->error(__('用户ID为空'));
        }
        if(empty($info_type))
        {
            $this->error(__('信息类型D为空'));
        }
       
        $data = ['title' => $title, 
                 'brand' => $brand,
                 'specs' =>  $specs,
                 'type' => $type,
                 'info_type'=>$info_type,
                 'price' => $price,
                 'trans_addr' => $trans_addr,
                 'req_contents' => $req_contents,
                 'detail_images' =>$detail_images,
                 'publish_time' => time(),
                 'createtime' => time(),
                 'updatetime' => time(),
                 'num' =>$num,
                 'user_id' => $user_id
                ];

        
        $id= Db::name('litestore_request')->insertGetId($data);

        Log::info("***********************************************************************addreq end*******************************************************");          
        $this->success('插入成功', ['id'=>$id
                        
      ]);
    }

      /**
     * 更新供求信息
     * @param title  标题
     * @param brand  品牌
     * @param specs  规格
     * @param type   类型
     * @param price  价格
     * @param trans_addr 交货地点
     * @param user_id 用户ID
     * @param req_contents 供求详情
     */
    public function updatereq()
    {
        Log::info("***********************************************************************updatereq start*******************************************************");          
        $title         = $this->request->post("title");
        $brand         = $this->request->post("brand");
        $specs         = $this->request->post("specs");
        $type          = $this->request->post("type");
        $price         = $this->request->post("price");
        $trans_addr    = $this->request->post("trans_addr");
        $user_id       = $this->request->post("user_id");
        $req_contents  = $this->request->post("req_contents");
        $info_type     = $this->request->post("info_type");
        $detail_images = $this->request->post("detail_images");
        $num           = $this->request->post("num");
        $id            = $this->request->post("id");

        
        Log::info("param info *****************************************");
        Log::info("id=".$id);                
        Log::info("title=".$title);
        Log::info("brand=".$brand);
        Log::info("specs=".$specs);
        Log::info("type=".$type);
        Log::info("price=".$price);
        Log::info("trans_addr=".$trans_addr);
        Log::info("user_id=".$user_id);
        Log::info("req_contents=".$req_contents);        
        Log::info("info_type=".$info_type);        
        Log::info("detail_images=".$detail_images);        
        Log::info("num=".$num);        
        Log::info("param info *****************************************");


        if(empty($title))
        {
            $this->error(__('供求标题不能为空'));
        }
        if(empty($brand))
        {
            $this->error(__('品牌不能为空'));
        }
        if(empty($specs))
        {
            $this->error(__('规格不能为空'));
        }

        if(empty($type))
        {
            $this->error(__('类型不能为空'));
        }

        if(strcmp($type,'1')<>0 && strcmp($type,'2') <>0)
        {
            $this->error(__('类型必须为1,或者2'));
        }

        if(empty($price))
        {
            $this->error(__('价格不能为空'));
        }

        if(empty($trans_addr))
        {
            $this->error(__('交货地点不能为空'));
        }

        if(empty($req_contents))
        {
            $this->error(__('供求详情不能为空'));
        }

        if(empty($user_id))
        {
            $this->error(__('用户ID为空'));
        }
        if(empty($info_type))
        {
            $this->error(__('信息类型D为空'));
        }
        if(empty($id))
        {
            $this->error(__('供求ID为空'));
        }
        
        $data = ['title' => $title, 
                 'brand' => $brand,
                 'specs' =>  $specs,
                 'type' => $type,
                 'info_type'=>$info_type,
                 'price' => $price,
                 'trans_addr' => $trans_addr,
                 'req_contents' => $req_contents,
                 'detail_images' =>$detail_images,
                 'updatetime' => time(),
                 'num' =>$num,
                ];
                $res = Db::table('fa_litestore_request')->where('id', $id)->update($data);
        Log::info("***********************************************************************updatereq end*******************************************************");                          
        $this->success("更新成功", ['res'=>$res] );
    }

     /**
     * 删除供求信息
  
     * @param user_id 用户ID
     * @param req_contents 供求详情
     */
    public function deletereq()
    {
        Log::info("***********************************************************************updatereq start*******************************************************");          
        $id            = $this->request->post("id");

        Log::info("param info *****************************************");
        Log::info("id=".$id);
        Log::info("param info *****************************************");

        $res = Db::table('fa_litestore_request')->where('id', $id)->delete();
        Log::info("***********************************************************************updatereq end*******************************************************");                          
        $this->success("更新成功", ['res'=>$res] );
    }


     /**
     * 增加意见反馈
     * @param title  标题
     * @param brand  品牌
     * @param specs  规格
     * @param type   类型
     * @param price  价格
     * @param trans_addr 交货地点
     * @param user_id 用户ID
     * @param req_contents 供求详情
     */
    public function addoption()
    {
        Log::info("***********************************************************************addoption start*******************************************************");                          
        $user_id   = $this->request->post("user_id");
        $req_contents = $this->request->post("req_contents");
        $option_type   = $this->request->post("option_type");
        $contact = $this->request->post("contact");
        $option_images   = $this->request->post("option_images");

        Log::info("param info *****************************************");
        Log::info("user_id=".$user_id);                
        Log::info("req_contents=".$req_contents);
        Log::info("option_type=".$option_type);
        Log::info("contact=".$contact);
        Log::info("option_images=".$option_images);
        Log::info("param info *****************************************");

        if(empty($req_contents))
        {
            $this->error(__('供求详情不能为空'));
        }
        if(empty($option_type))
        {
            $this->error(__('反馈类型不能为空'));
        }

        if(empty($contact))
        {
            $this->error(__('联系方式不能为空'));
        }

        if(empty($user_id))
        {
            $this->error(__('用户ID为空'));
        }
        $data = ['req_contents' => $req_contents,
                'option_type' => $option_type,
                'contact' => $contact,
                'option_images' => $option_images,
                 'createtime' => time(),
                 'updatetime' => time(),
                 'user_id' => $user_id
                ];
        
        $id= Db::name('litestore_option')->insertGetId($data);
        Log::info("***********************************************************************addoption end*******************************************************");                          
        $this->success('插入成功', ['id'=>$id
                        
      ]);
    }

    
    public function Updata_user_hawk(){
        Log::info("***********************************************************************Updata_user_hawk start*******************************************************");                          
        $userInfo = $this->request->post("userInfo");
        $mobile = $this->request->post("mobile");
        if (!$userInfo||!$this->token) {
            $this->error("参数不正确");
        }

        $this->auth->init($this->token);
        //检测是否登录
        if ($this->auth->isLogin()) {
            $user = $this->auth->getUser();
            $fields = [];
            $userInfo = json_decode($userInfo,true);
            $fields['avatar'] = $userInfo['avatarUrl'];
            $fields['nickname'] = $userInfo['nickName'];
            $fields['mobile'] = $mobile;
            $user->save($fields);
            Log::info("***********************************************************************Updata_user_hawk end*******************************************************");                          
            $this->success("已经登录", ['userInfo' => $this->auth->getUserinfo()] );
        }else{
            $this->error("未登录状态");
        }
    }

    public function login()
    {
        $config = get_addon_config('litestore');
        $code = $this->request->post("code");
        if (!$code) {
            $this->error("参数不正确");
        }
        Log::info("***********************************************************************login start*******************************************************");
        Log::info(" login  start code== ".$code);
        


        $params = [
            'appid'      => $config['AppID'],
            'secret'     => $config['AppSecret'],
            'js_code'    => $code,
            'grant_type' => 'authorization_code'
        ];
        $result = Http::sendRequest("https://api.weixin.qq.com/sns/jscode2session", $params, 'GET');
        if ($result['ret']) {
            $json = (array)json_decode($result['msg'], true);
            if (isset($json['openid'])) {
                //如果有传Token
                if ($this->token) {
                    $this->auth->init($this->token);
                    //检测是否登录
                    if ($this->auth->isLogin()) {
                        $third = Third::where(['openid' => $json['openid'], 'platform' => 'wxapp'])->find();
                        if ($third && $third['user_id'] == $this->auth->id) {
                            //把最新的 session_key 保存到 第三方表的 access_token 里
                            $third['access_token'] = $json['session_key'];
                            $third->save();
                            //$this->success("登录成功", $this->Format_avatarUrl($this->auth->getUserinfo()));
                        }
                    }
                }
                $third_result =Db::query('select * from fa_third where openid=:openid',['openid'=>$json['openid']]);
                if(!empty($third_result))
                {
                    Db::table('fa_third')->where('openid', $json['openid'])->update(['access_token'=>$json['session_key'],'updatetime'=>time(),'logintime'=>time()]);
                    Log::info("***********************************************************************login end1*******************************************************");
                    $this->success("登录成功", ['openid'=>$json['openid'],'session_key'=>$json['session_key']]);
                }

                $platform = 'wxapp';
                $result = [
                    'openid'        => $json['openid'],
                    'userinfo'      => [
                        'nickname' => '游客未认证',
                    ],
                    'access_token'  => $json['session_key'],
                    'refresh_token' => '',
                    'expires_in'    => isset($json['expires_in']) ? $json['expires_in'] : 0,
                ];
                $extend = ['mobile'=>'NoLoginData' ,'gender' => '0', 'nickname' => '游客未认证', 'card_tpl_id' => '1',
                'card_tpl_image'=>'/uploads/20200920/249d96e7918477d503cc4f9c9790f507.jpg',
                'email'=>'111212@qq.com',
                'status'=>'normal',
                 'avatar' =>'/uploads/20200823/ph.png'];
                $ret = Service::connect_hawk($platform, $result, $extend);
                if ($ret) {
                    $auth = Auth::instance();
                    //$this->success("登录成功", $this->Format_avatarUrl($this->auth->getUserinfo()));
                    Log::info("***********************************************************************login end*******************************************************");
                    $this->success("登录成功", ['openid'=>$json['openid'],'session_key'=>$json['session_key']]);

                } else {
                    $this->error("连接失败");
                }
            } else {
                $this->error("登录失败",$json);
            }
        }

        return;
    }

    /**
     * 根据openid获取用户信息
     */
    public function getuserinfobyopenid()
    {
        $openid = $this->request->post("openid");
        Log::info("***********************************************************************getuserinfobyopenid start*******************************************************");

        Log::info("param info *****************************************");
        Log::info("openid=".$openid);
        Log::info("param info *****************************************");

       
        if (!$openid) {
            $this->error("输入的openid参数为空");
        }
        $third_result =Db::query('select * from fa_third where openid=:openid',['openid'=>$openid]);
        if(empty($third_result))
        {
            $this->error("用户信息不存在");
        }
        $user_id = $third_result[0]['user_id'];
        $user =Db::query('select * from fa_user where id=:user_id',['user_id'=>$user_id]);
        if(empty($user))
        {
            $this->error("用户信息不存在");
        }

        Log::info("effect_end_time==".$user[0]['effect_end_time']);
        if(!empty($user[0]['effect_end_time']))
        {
            $now = date('Ymd',time());  
            $eff_date = str_replace('-','',$user[0]['effect_end_time']);
            Log::info("now==".$now);
            Log::info("eff_date==".$eff_date);

            if(intval($now)> intval($eff_date))
            {
                Log::info(">>>>>>>>>>>>>>>>>>>>>>>>> *****************************************");
                Db::execute("update fa_user set level='1' where id = ".$user[0]['id']."",[]);
            }
        }

        $user[0]['avatar'] =$this->format_cdnurl($user[0]['avatar']);
        $user[0]['businesslicense_images'] = $this->format_cdnurl($user[0]['businesslicense_images']);
        $user[0]['card_tpl_image'] = $this->format_cdnurl($user[0]['card_tpl_image']);

        $user[0]['profile_images'] = $this->format_cdnurl($user[0]['profile_images']);

        $iarr =  $user[0]['profile_images'] ;
        if(!empty($iarr)){
            $images=explode(',',$iarr);
            $num = count($images);
            for($i=0;$i<$num;$i++){
                $images[$i]=empty($images[$i])?"":cdnurl($images[$i],true);
            }
            $user[0]['profile_images'] = $images;
        }else {
            $user[0]['profile_images'] = [];
        }


        Log::info("param info *****************************************");
        Log::info($user[0]);
        Log::info("param info *****************************************");


        Log::info("***********************************************************************getuserinfobyopenid end*******************************************************");
        $this->success("获取成功", ['userinfo' =>$user[0]]);
        
    }
    /**
     * 获取技术资料信息列表 
     * 
     */
    public function techdoclist()
    {
        Log::info("***********************************************************************techdoclist start*******************************************************");
        $page = empty( $this->request->post("currpage")) ? 1 :  $this->request->post("currpage");//获取当前页数
        $title = empty( $this->request->post("title")) ? '' :  $this->request->post("title");//资料标题
        $techtype = empty( $this->request->post("techtype")) ? '' :  $this->request->post("techtype");//技术资料类型:0=机器维修,1=生产工艺,2=原材料处理,3=其他

        
        Log::info("param info *****************************************");
        Log::info("page=".$page);
        Log::info("title=".$title);
        Log::info("techtype=".$techtype);
        Log::info("param info *****************************************");

        //组装查询条件
        $where =[];
        if(!empty($title))
        {
            $where['title'] = array('like','%'.$title.'%');
        }
        if(!empty($techtype))
        {
            $where['techtype'] = $techtype;
        }


        
        //进行查询
        $techsearchlist = Db::name('litestore_tech_data')->where($where)->alias('a')->page($page,10)->select();
        $count = Db::name('litestore_tech_data')->where($where)->count();//有多少条数据
        $tatal = ceil($count/10);//要分多少页
        $techsearchlist2 = [];

        //结果封装
        foreach ($techsearchlist as $index => $item) {

            $data = pathinfo($item['tech_file']);

            $doctype='';
            if(strtolower($data['extension'])=='doc'||$data['extension']=='docx')
            {
                $doctype ='1';
            }
            if(strtolower($data['extension'])=='pdf')
            {
                $doctype ='2';
            }
            if(strtolower($data['extension'])=='ppt' ||strtolower($data['extension'])=='pptx')
            {
                $doctype ='3';
            }
                $techsearchlist2[] = [
                    'id'=> $item['id'],
                    'title'=> $item['title'],
                    'techtype'=> $item['techtype'],
                    'user_id'=> $item['user_id'],            
                    'tech_file'=> $this->format_cdnurl($item['tech_file']),
                    'exttype'=>  $doctype,
                    'createtime'=> $item['createtime'],
                    'updatetime'=> $item['createtime'],
                    
                ];
            
        }
        Log::info("result info *****************************************");
        Log::info($techsearchlist2);
        Log::info("result info *****************************************");


        Log::info("***********************************************************************techdoclist end*******************************************************");
        $this->success('获取成功', [
                        'techdoclist'=>$techsearchlist2,
                        'tatal'=>$tatal,
                        'currpage'=>$page
                        ]);
    }


    /**
     * 获取名录信息列表 
     * 
     */
    public function directorylist()
    {
        Log::info("**********************************************************************************directorylist  start *************************************************************** ");
        $page = empty( $this->request->post("currpage")) ? 1 :  $this->request->post("currpage");//获取当前页数
        
        $keyword = empty( $this->request->post("keyword")) ? '' :  $this->request->post("keyword");//资料标题

        $area = empty( $this->request->post("area")) ? '' :  $this->request->post("area");//区域

        $group_id = empty( $this->request->post("group_id")) ? '' :  $this->request->post("group_id");//角色组

        $level = empty( $this->request->post("level")) ? '' :  $this->request->post("level");//会员等级

        $user_id = empty( $this->request->post("user_id")) ? '' :  $this->request->post("user_id");//区域

        Log::info("param info start *****************************************");
        Log::info("directorylist  page==".$page);
        Log::info("directorylist  keyword==".$keyword);
        Log::info("directorylist  area==".$area);
        Log::info("directorylist  group_id==".$group_id);
        Log::info("directorylist  level==".$level);
        Log::info("directorylist  user_id==".$user_id);
        Log::info("param info end *****************************************");

        if(empty($user_id))
        {
            $this->error("用户ID必须输入");
        }

     
        $where ="1=1 " ;
        if( !empty($area)){
            //$where['region_city'] =    array('like','%'.$area.'%');
            $where=$where." and region_city like '%".$area."%'";
        }
        if( !empty($group_id)){
            //$where['group_id'] = $group_id;
            $where=$where." and group_id = '".$group_id."'";
        }
        if( !empty($level)){ 
            $where=$where." and level = '".$level."'";

           // $where['level'] = $level;
        }
        if(empty($group_id)){
            //$where['group_id'] = array('in',array('2','3','4','5','6'));
             $where=$where." and group_id in('2','3','4','5','6','8')";

        }
        $userList = Db::name('user')->where(['id'=>$user_id])->alias('b')->select();
        if(empty($userList))
        {
            $this->error("用户ID未查找到记录");
        }
        $userLevel = $userList[0]['certify_status'];


        $pagenum =10;
        if($userLevel=='1')//未认证会员
        {
            $pagenum =10;
        }
        $where =$where." and appr_status ='5' and certify_status='3' and status='normal' ";
        $where=$where.str_replace('keyword',$keyword,'and (businessscope like "%keyword%" OR nickname like "%keyword%" OR companyprofile like "%keyword%" OR companyname like "%keyword%")');
        Log::info('where =='.$where);
        $directorylist = Db::name('user')->where($where)->alias('a')->order('level desc,score desc')->page($page,$pagenum)->select();

        $count = Db::name('user')->where($where)->count();//有多少条数据
        $tatal = ceil($count/$pagenum);//要分多少页
        if($userLevel=='1')//未认证会员
        {   
            $tatal=1;
        }
    
        foreach ($directorylist as $index => $item) {
            
            $directorylist[$index] = [
                'id'=> $item['id'],
                'group_id'=> $item['group_id'],
                'nickname'=> $item['nickname'],
                'mobile'=> $item['mobile'],
                'level'=> $item['level'],
                'region_city'=> $item['region_city'],
                'score'=> $item['score'],
                'companyname'=> $item['companyname'],
                'businessscope'=> $item['businessscope'],
                'createtime'=> $item['createtime'],
                'updatetime'=> $item['createtime']
             ];
        }
        Log::info("result info *****************************************");
        Log::info($directorylist);
        Log::info("result info *****************************************");


        Log::info("**********************************************************************************directorylist  end *************************************************************** ");
        $this->success('获取成功', ['directorylist'=>$directorylist,'tatal'=>$tatal,'currpage'=>$page]);
    }


     /**
     * 获取技工信息列表 
     * 
     */
    public function workderlist()
    {
        Log::info("**********************************************************************************workderlist  start *************************************************************** ");
        $currpage = empty( $this->request->post("currpage")) ? 1 :  $this->request->post("currpage");//获取当前页数
        
        $keyword = empty( $this->request->post("experience")) ? '' :  $this->request->post("experience");//资料标题

        $area = empty( $this->request->post("region_city")) ? '' :  $this->request->post("region_city");//区域

        $user_id = empty( $this->request->post("user_id")) ? '' :  $this->request->post("user_id");//区域
       
        Log::info("param info start *****************************************");
        Log::info("  page==".$currpage);
        Log::info("  keyword==".$keyword);
        Log::info("  area==".$area);
        Log::info("  user_id==".$user_id);
        Log::info("param info end *****************************************");

        if(empty($user_id))
        {
            $this->error("用户ID必须输入");
        }
        $orwhere =str_replace('keyword',$keyword," and (experience like '%keyword%' or nickname like '%keyword%' or work like '%keyword%' or companyname like '%keyword%') ");
        
        $where ="1=1 ";
        if( !empty($area)){ 
            $where=$where." and region_city like '%".$area."%'";
        }
        if( !empty($group_id)){
          
            $where=$where." and group_id = '".$group_id."'";

        }
        if( !empty($level)){
            $where=$where." and level = '".$level."'";
           
        }
       
        $where =$where ." and group_id='7' and status='normal' and appr_status='4' and certify_status='2' ";//7 生产师父 4个人审批通过 2个人认证

        $where =$where .$orwhere;
        
        $userList = Db::name('user')->where(['id'=>$user_id])->alias('b')->select();
        if(empty($userList))
        {   
            $this->error("用户ID未查找到记录");
        }
        $userLevel = $userList[0]['certify_status'];
        $pagenum =10;
        if($userLevel=='1')//未认证会员
        {
            $pagenum =10;
        }
        Log::info('where=='.$where);
        $directorylist = Db::name('user')->where($where)->alias('a')->page($currpage,$pagenum)->select();

        $count = Db::name('user')->where($where)->count();//有多少条数据

        $tatal = ceil($count/$pagenum);//要分多少页
        if($userLevel=='1')//未认证会员
        {   
            $tatal=1;
        }

    
        foreach ($directorylist as $index => $item) {

            $directorylist[$index] = [
                'id'=> $item['id'],
                'avatar'=> $item['avatar'],
                'nickname'=> $item['nickname'],
                'mobile'=> $item['mobile'],
                'level'=> $item['level'],
                'work'=> $item['work'],
                'experience'=> $item['experience'],
                'address'=> $item['address'],
                'region_city'=> $item['region_city'],
                'companyname'=> $item['companyname'],
                'businessscope'=> $item['businessscope'],
                'createtime'=> $item['createtime'],
                'updatetime'=> $item['createtime']
             ];
        }
        Log::info("**********************************************************************************workderlist  end *************************************************************** ");
        $this->success('获取成功', [
                        'directorylist'=>$directorylist,
                        'tatal'=>$tatal,
                        'currpage'=>$currpage
                        ]);
    }

    

      /**
     * 根据user_id获取名录信息详情信息
     */
    public function directorydetail()
    {
        Log::info("**********************************************************************************directorydetail  start *************************************************************** ");
        $user_id = $this->request->post("id");
        if (!$user_id) {
            $this->error("输入的id参数为空");
        }

        Log::info("  user_id==".$user_id);

        $user_result =Db::query('select id,group_id,profile_images,nickname,mobile,avatar,level,region_city,address,work,experience,companyname,businessscope,businesslicense_images,companyprofile,card_tpl_id,certify_status,effect_start_time,effect_end_time from fa_user where id=:user_id',['user_id'=>$user_id]);
        if(empty($user_result))
        {
            $this->error("名录信息不存在");
        }
      //  $user_result[0]['avatar']=$this->format_cdnurl( $user_result[0]['avatar']);

        $iarr =  $user_result[0]['profile_images'] ;
        if(!empty($iarr)){
            $images=explode(',',$iarr);
            $num = count($images);
            for($i=0;$i<$num;$i++){
                $images[$i]=empty($images[$i])?"":$this->format_cdnurl($images[$i]);
            }
            $user_result[0]['profile_images'] = $images;
        }else {
            $user_result[0]['profile_images'] = [];
        }



        Log::info("**********************************************************************************directorydetail  end *************************************************************** ");
        $this->success("获取成功", [
            'detail' =>$user_result[0]]);
        
    }
   /**
     * 获取技术回答信息列表 
     * 
     * @param $page 当前页数
     * @param qs_contents 技术回答内容
     */
    public function techquestionlist()
    {
        Log::info("**********************************************************************************techquestionlist  start *************************************************************** ");
        $page = empty( $this->request->post("currpage")) ? 1 :  $this->request->post("currpage");//获取当前页数
        $qs_contents = empty( $this->request->post("qs_contents")) ? '' :  $this->request->post("qs_contents");//资料标题


        Log::info("  page==".$page);
        Log::info("  qs_contents==".$qs_contents);

        $where =[];
        if(!empty($qs_contents))
        {
            $where['qs_contents'] = array('like','%'.$qs_contents.'%');
        }
        if(!empty($qs_type))
        {
            $where['qs_type'] = $qs_type;
        }
        $field ='a.id,a.user_id,b.avatar,b.nickname,b.mobile,a.qs_type,a.qs_images,a.qs_contents,a.as_num,a.qs_status,a.createtime,a.updatetime ';
        $techsearchlist = Db::name('litestore_tech_question')->alias('a')->join('user b','b.id=a.user_id','left')->field($field)->where($where)->page($page,10)->select();
        $count = Db::name('litestore_tech_question')->alias('a')->join('user b','b.id=a.user_id','left')->where($where)->count();//有多少条数据
         $tatal = ceil($count/10);//要分多少页
        
        $techquestionlist2 = [];
        
        foreach ($techsearchlist as $index => $item) {
            $images=explode(',',$item['qs_images']);
            $num = count($images);

            for($i=0;$i<$num;$i++){
                $images[$i]=$this->format_cdnurl($images[$i]);
            }
            if(empty($item['avatar'])){$item['avatar']=cdnurl('/uploads/20200823/ph.png',true);}
          //  $item['createtime'] = strtotime(date('Y-m-d',$item['createtime']));
          //  $item['updatetime'] = strtotime(date('Y-m-d',$item['updatetime']));
            if((time()-$item['createtime'])/3600<24){ $ts =(time()-$item['createtime'])/3600 .'小时前';}else {$ts =round(( time()-$item['createtime'])/3600/24).'天前';}

            $techquestionlist2[] = [
                'id'=> $item['id'],
                'user_id'=> $item['user_id'],
                'avatar'=> $this->format_cdnurl($item['avatar']),
                'nickname'=> $item['nickname'],
                'mobile'=> $item['mobile'],
                'qs_type'=> $item['qs_type'],
                'user_id'=> $item['user_id'],            
                'qs_images'=>$images, 
                'qs_contents'=> $item['qs_contents'],
                'as_num'=> $item['as_num'],
                'qs_status'=>$item['qs_status'],
                'ts'=>$ts,   
                'createtime'=> $item['createtime'],
                'updatetime'=> $item['updatetime']
             ];
        }
        Log::info("**********************************************************************************techquestionlist  end *************************************************************** ");
        $this->success('获取成功', ['techquestionlist'=>$techquestionlist2,'tatal'=>$tatal,'currpage'=>$page]);
    }    

    /**
     * 获取技术回答信息列表 
     * 
     * @param $page 当前页数
     * @param qs_contents 技术回答内容
     */
    public function mytechquestionlist()
    {
        Log::info("**********************************************************************************mytechquestionlist  start *************************************************************** ");
        $page = empty( $this->request->post("currpage")) ? 1 :  $this->request->post("currpage");//获取当前页数
        $user_id = empty( $this->request->post("user_id")) ? '' :  $this->request->post("user_id");//资料标题


        Log::info("  page==".$page);
        Log::info("  user_id==".$user_id);

        $where =[];
        if(!empty($user_id))
        {
            $where['user_id'] = $user_id;
        }

        $field ='a.id,a.user_id,b.avatar,b.nickname,b.mobile,a.qs_type,a.qs_images,a.qs_contents,a.as_num,a.qs_status,a.createtime,a.updatetime ';
        $techsearchlist = Db::name('litestore_tech_question')->alias('a')->join('user b','b.id=a.user_id','left')->field($field)->where($where)->page($page,10)->select();
        $count = Db::name('litestore_tech_question')->alias('a')->join('user b','b.id=a.user_id','left')->where($where)->count();//有多少条数据
         $tatal = ceil($count/2);//要分多少页
        
        $techquestionlist2 = [];
        
        foreach ($techsearchlist as $index => $item) {
            $images=explode(',',$item['qs_images']);
            $num = count($images);

            for($i=0;$i<$num;$i++){
                $images[$i]=cdnurl($images[$i],true);
            }
            if(empty($item['avatar'])){$item['avatar']=$this->format_cdnurl('/uploads/20200823/ph.png');}
         //   $item['createtime'] = strtotime(date('Y-m-d',$item['createtime']));
         //   $item['updatetime'] = strtotime(date('Y-m-d',$item['updatetime']));
            if((time()-$item['createtime'])/3600<24){ $ts =(time()-$item['createtime'])/3600 .'小时前';}else {$ts =round(( time()-$item['createtime'])/3600/24).'天前';}

            $techquestionlist2[] = [
                'id'=> $item['id'],
                'user_id'=> $item['user_id'],
                'avatar'=>$this->format_cdnurl($item['avatar']),
                'nickname'=> $item['nickname'],
                'mobile'=> $item['mobile'],
                'qs_type'=> $item['qs_type'],
                'user_id'=> $item['user_id'],            
                'qs_images'=>$images, 
                'qs_contents'=> $item['qs_contents'],
                'as_num'=> $item['as_num'],
                'qs_status'=>$item['qs_status'],
                'ts'=>$ts,   
                'createtime'=> $item['createtime'],
                'updatetime'=> $item['updatetime']
             ];
        }
        Log::info("**********************************************************************************mytechquestionlist  end *************************************************************** ");
        $this->success('获取成功', [
                        'techquestionlist'=>$techquestionlist2,
                        'tatal'=>$tatal,
                        'currpage'=>$page
                        ]);
    }    

    /**
     * 个人认证
     */
    public function personalauth()
    {
        Log::info("**********************************************************************************personalauth  start *************************************************************** ");
        $user_id        = $this->request->post("user_id");         //姓名
        $nickname       = $this->request->post("nickname");        //姓名
        $mobile         = $this->request->post("mobile");          //手机号码
        $address        = $this->request->post("address");         //地址
        $work           = $this->request->post("work");            //从事工作
        $experience     = $this->request->post("experience");      //技能及工作经验
        $companyname    = $this->request->post("companyname");     //企业名称
        $region_city    = $this->request->post("region_city");     //省市区
        $avatar         =empty($this->request->post("avatar"))?"": $this->request->post("avatar"); //获取个人头像信息
        Log::info("personalauth start ");

        
        Log::info("  user_id==".$user_id);
        Log::info("  nickname==".$nickname);
        Log::info("  mobile==".$mobile);
        Log::info("  address==".$address);
        Log::info("  work==".$work);
        Log::info("  experience==".$experience);
        Log::info("  companyname==".$companyname);
        Log::info("  region_city==".$region_city);
        Log::info("  avatar==".$avatar);


        $updatedata =[];
        if (!$user_id) {
            $this->error("用户ID不能为空");
        }
        if (!$nickname) {
            $this->error("姓名不能为空");
        }else{ 
            $updatedata['nickname']=$nickname;
        }
        if (!$mobile) {
            $this->error("手机号码不能为空");
        }
        else{
            $updatedata['mobile']=$mobile;
        }
        if (!$address) {
            $this->error("地址不能为空");
        }
        else{
            $updatedata['address']=$address;
        }
        if (!$work) {
            $this->error("从事工作不能为空");
        }
        else{
            $updatedata['work']=$work;
        }
        if (!$experience) {
            $this->error("技能及工作经验不能为空");
        }
        else{
            $updatedata['experience']=$experience;
        }
        if (!$region_city) {
            $this->error("省市区不能为空");
        }
        else{
            $updatedata['region_city']=$region_city;
        }
        if (!$companyname) {
            $this->error("企业名称不能为空");
        }
        else{
            $updatedata['companyname']=$companyname;
        }
        if(!empty($avatar)){
            $updatedata['avatar'] =empty($avatar)?"/uploads/20200823/ph.png":$this->saveheadimgurl($user_id,$avatar); 
        }
        $now = date('Y-m-d',time());  
        $oneyear =  date("Y-m-d",strtotime("-1days",strtotime("+12months",strtotime(date('Y-m-d H:i:s',time())))));


        //$updatedata['effect_start_time']=$now;
        //$updatedata['effect_end_time']=$oneyear;

        $userInfo = Db::query("select * from fa_user where id=:user_id limit 1 ",['user_id'=>$user_id]);
        if(empty($userInfo))
        {
                 $this->error(__('根据用户ID查找用户信息不存在'));
        }

        if($userInfo[0]['appr_status']!='4'&& $userInfo[0]['appr_status']!='5'){
            $updatedata['certify_status']='2';
            $updatedata['group_id']='7';
            $updatedata['appr_status']='4';//个人认证默认审核通过
        }

        $res = Db::table('fa_user')->where('id', $user_id)->update($updatedata);

        Log::info("**********************************************************************************personalauth  end *************************************************************** ");
        $this->success("更新成功", ['res'=>$res] );
    }

    /**
     * 名片信息修改
     */
    public function updatecardinfo()
    {
        Log::info("**********************************************************************************updatecardinfo  start *************************************************************** ");
        $user_id        = $this->request->post("user_id");         //用户ID
        $nickname       = $this->request->post("nickname");        //姓名
        $mobile         = $this->request->post("mobile");          //手机号码
        $address        = $this->request->post("address");         //地址
        $work           = $this->request->post("work");            //从事工作
        $experience     = $this->request->post("experience");      //技能及工作经验
        $companyname    = $this->request->post("companyname");     //企业名称
        $region_city    = $this->request->post("region_city");     //省市区
        Log::info("updatecardinfo start ");

        Log::info("  user_id==".$user_id);
        Log::info("  nickname==".$nickname);
        Log::info("  mobile==".$mobile);
        Log::info("  address==".$address);
        Log::info("  work==".$work);
        Log::info("  experience==".$experience);
        Log::info("  companyname==".$companyname);
        Log::info("  region_city==".$region_city);

        $updatedata =[];
        if (!$user_id) {
            $this->error("用户ID不能为空");
        }
        if (!$nickname) {
            $this->error("姓名不能为空");
        }else{ 
            $updatedata['nickname']=$nickname;
        }
        if (!$mobile) {
            $this->error("手机号码不能为空");
        }
        else{
            $updatedata['mobile']=$mobile;
        }
        if (!$address) {
            $this->error("地址不能为空");
        }
        else{
            $updatedata['address']=$address;
        }
        if (!$work) {
            $this->error("从事工作不能为空");
        }
        else{
            $updatedata['work']=$work;
        }
        if (!$experience) {
            $this->error("技能及工作经验不能为空");
        }
        else{
            $updatedata['experience']=$experience;
        }
        if (!$region_city) {
            $this->error("省市区不能为空");
        }
        else{
            $updatedata['region_city']=$region_city;
        }
        if (!$companyname) {
            $this->error("企业名称不能为空");
        }
        else{
            $updatedata['companyname']=$companyname;
        }
        $res = Db::table('fa_user')->where('id', $user_id)->update($updatedata);
        Log::info("**********************************************************************************updatecardinfo  end *************************************************************** ");
        $this->success("更新成功", ['res'=>$res] );
    }

    /**
     * 企业认证
     */
    public function enterpriseauth()
    {
        Log::info("**********************************************************************************enterpriseauth  start *************************************************************** ");
        $user_id                = $this->request->post("user_id");                //用户ID
        $companyname            = $this->request->post("companyname");            //企业名称
        $businessscope          = $this->request->post("businessscope");          //经营范围
        $businesslicense_images = $this->request->post("businesslicense_images"); //营业执照
        $tel                    = $this->request->post("tel");                    //公司电话号码
        $companyprofile         = $this->request->post("companyprofile");         //企业介绍
        $region_city            = $this->request->post("region_city");            //公司电话号码
        $group_id               = $this->request->post("group_id");               //企业类型
        


        Log::info("  user_id==".$user_id);
        Log::info("  companyname==".$companyname);
        Log::info("  businessscope==".$businessscope);
        Log::info("  businesslicense_images==".$businesslicense_images);
        Log::info("  tel==".$tel);
        Log::info("  companyprofile==".$companyprofile);
        Log::info("  region_city==".$region_city);
        Log::info("  group_id==".$group_id);

        $updatedata['updatetime'] =time();

        if (empty($user_id)) {
            $this->error("用户ID不能为空");
        }
        if (empty($group_id)) {
            $this->error("企业类型不能为空");
        }else
        {
            $updatedata['group_id'] =$group_id;
        }
        if (empty($companyname)) {
            $this->error("企业名称不能为空");
        }else{
            $updatedata['companyname'] =$companyname;
        }
        if (empty($businessscope)) {
            $this->error("经营范围不能为空");
        }else{
            $updatedata['businessscope'] =$businessscope;
        }
        if (empty($businesslicense_images)) {
            $this->error("营业执照不能为空");
        }else{
            $updatedata['businesslicense_images'] =$businesslicense_images;
        }
       
        if (!$companyprofile) {
            $this->error("企业介绍不能为空");
        }
        else{
            $updatedata['companyprofile'] =$companyprofile;
        }
        if (!$region_city) {
            $this->error("省市县不能为空");
        }
        else{
            $updatedata['region_city'] =$region_city;
        }
        $now = date('Y-m-d',time());
        $oneyear =  date("Y-m-d",strtotime("-1days",strtotime("+3months",strtotime(date('Y-m-d H:i:s',time())))));
       // $updatedata['effect_start_time']='';
       // $updatedata['effect_end_time']='';

        $updatedata['certify_status']='3';
        $updatedata['appr_status']='3';//企业认证状态 3=企业认证审核中 后台进行审核后 改成 5=企业审核通过

        $res=Db::table('fa_user')->where('id', $user_id)->update($updatedata);
        Log::info("**********************************************************************************enterpriseauth  end *************************************************************** ");
        $this->success("更新成功", ['result'=>$res] );
    }

    /**
     * 更改企业信息
     */
    public function updateenterpriseinfo()
    {
        Log::info("**********************************************************************************updateenterpriseinfo  start *************************************************************** ");
        $user_id                = $this->request->post("user_id");                //用户ID
        $businessscope          = $this->request->post("businessscope");          //经营范围
        $companyprofile         = $this->request->post("companyprofile");         //企业介绍
        $profile_images         = $this->request->post("profile_images");         //企业图片介绍
        $region_city            = $this->request->post("region_city");            //地区
        

        Log::info("  user_id==".$user_id);
        Log::info("  companyprofile==".$companyprofile);
        Log::info("  businessscope==".$businessscope);
        Log::info("  profile_images==".$profile_images);
        Log::info("  region_city==".$region_city);
        

        
        $updatedata['updatetime'] =time();

        if (empty($user_id)) {
            $this->error("用户ID不能为空");
        }
        if (empty($businessscope)) {
            $this->error("经营范围不能为空");
        }else{
            $updatedata['businessscope'] =$businessscope;
        }
       
        if (!$companyprofile) {
            $this->error("企业介绍不能为空");
        }
        else{
            $updatedata['companyprofile'] =$companyprofile;
        }
        if (!$region_city) {
            $this->error("省市县不能为空");
        }
        else{
            $updatedata['region_city'] =$region_city;
        }
        if (!empty($businessscope)) {
            $updatedata['profile_images'] =$profile_images;
        }
        $updatedata['updatetime'] =time();
        $res=Db::table('fa_user')->where('id', $user_id)->update($updatedata);
        Log::info("**********************************************************************************updateenterpriseinfo  end *************************************************************** ");
        $this->success("更新成功", ['result'=>$res] );
    }

    /**
     * 更新用户头像     
     * @param user_id 用户ID
     * @param avatar  用户头像地址
     * 
     */
    public function updateavatar()
    {
        Log::info("**********************************************************************************updateavatar  start *************************************************************** ");
        $user_id = $this->request->post("user_id");//用户ID
        $avatar = $this->request->post("avatar");//企业名称


        Log::info("  user_id==".$user_id);
        Log::info("  avatar==".$avatar);
        

        $updatedata['updatetime'] =time();
        if (empty($user_id)) {
            $this->error("用户ID不能为空");
        }
        if (empty($avatar)) {
            $this->error("头像信息不能为空");
        }else
        {
            $updatedata['avatar'] =$this->saveheadimgurl($user_id,$avatar);
        }
        $res=Db::table('fa_user')->where('id', $user_id)->update($updatedata);
        Log::info("**********************************************************************************updateavatar  end *************************************************************** ");
        $this->success("更新成功", ['result'=>$res] );
    }

    

   /**
     * 上传文件
     * @ApiMethod (POST)
     * @param File $file 文件流
     */
    public function upload()
    {
        Log::info("**********************************************************************************upload  start *************************************************************** ");
        $file = $this->request->file('file');
        if (empty($file)) {
            $this->error(__('没有上传文件！'));
        }

        //判断是否已经存在附件
        $sha1 = $file->hash();

        $upload = Config::get('upload');

        preg_match('/(\d+)(\w+)/', $upload['maxsize'], $matches);
        $type = strtolower($matches[2]);
        $typeDict = ['b' => 0, 'k' => 1, 'kb' => 1, 'm' => 2, 'mb' => 2, 'gb' => 3, 'g' => 3];
        $size = (int)$upload['maxsize'] * pow(1024, isset($typeDict[$type]) ? $typeDict[$type] : 0);
        $fileInfo = $file->getInfo();
        $suffix = strtolower(pathinfo($fileInfo['name'], PATHINFO_EXTENSION));
        $suffix = $suffix && preg_match("/^[a-zA-Z0-9]+$/", $suffix) ? $suffix : 'file';

        $mimetypeArr = explode(',', strtolower($upload['mimetype']));
        $typeArr = explode('/', $fileInfo['type']);

        //禁止上传PHP和HTML文件
        if (in_array($fileInfo['type'], ['text/x-php', 'text/html']) || in_array($suffix, ['php', 'html', 'htm'])) {
            $this->error(__('上传文件格式错误！'));
        }
        //验证文件后缀
        if ($upload['mimetype'] !== '*' &&
            (
                !in_array($suffix, $mimetypeArr)
                || (stripos($typeArr[0] . '/', $upload['mimetype']) !== false && (!in_array($fileInfo['type'], $mimetypeArr) && !in_array($typeArr[0] . '/*', $mimetypeArr)))
            )
        ) {
            $this->error(__('上传文件格式错误！'));
        }
        //验证是否为图片文件
        $imagewidth = $imageheight = 0;
        if (in_array($fileInfo['type'], ['image/gif', 'image/jpg', 'image/jpeg', 'image/bmp', 'image/png', 'image/webp']) || in_array($suffix, ['gif', 'jpg', 'jpeg', 'bmp', 'png', 'webp'])) {
            $imgInfo = getimagesize($fileInfo['tmp_name']);
            if (!$imgInfo || !isset($imgInfo[0]) || !isset($imgInfo[1])) {
                $this->error(__('Uploaded file is not a valid image'));
            }
            $imagewidth = isset($imgInfo[0]) ? $imgInfo[0] : $imagewidth;
            $imageheight = isset($imgInfo[1]) ? $imgInfo[1] : $imageheight;
        }

        
        $replaceArr = [
            '{year}'     => date("Y"),
            '{mon}'      => date("m"),
            '{day}'      => date("d"),
            '{hour}'     => date("H"),
            '{min}'      => date("i"),
            '{sec}'      => date("s"),
            '{random}'   => Random::alnum(16),
            '{random32}' => Random::alnum(32),
            '{filename}' => $suffix ? substr($fileInfo['name'], 0, strripos($fileInfo['name'], '.')) : $fileInfo['name'],
            '{suffix}'   => $suffix,
            '{.suffix}'  => $suffix ? '.' . $suffix : '',
            '{filemd5}'  => md5_file($fileInfo['tmp_name']),
        ];
     
        $savekey = $upload['savekey'];
        $savekey = str_replace(array_keys($replaceArr), array_values($replaceArr), $savekey);

        $uploadDir = substr($savekey, 0, strripos($savekey, '/') + 1);
        $fileName = substr($savekey, strripos($savekey, '/') + 1);
        
        $splInfo = $file->validate(['size' => $size])->move(ROOT_PATH . '/public' . $uploadDir, $fileName);
        if ($splInfo) {
            $params = array(
                'admin_id'    => 0,
                'user_id'     => (int)$this->auth->id,
                'filesize'    => $fileInfo['size'],
                'imagewidth'  => $imagewidth,
                'imageheight' => $imageheight,
                'imagetype'   => $suffix,
                'imageframes' => 0,
                'mimetype'    => $fileInfo['type'],
                'url'         => $uploadDir . $splInfo->getSaveName(),
                'uploadtime'  => time(),
                'storage'     => 'local',
                'sha1'        => $sha1,
            );
            $attachment = model("attachment");
            $attachment->data(array_filter($params));
            $attachment->save();
            \think\Hook::listen("upload_after", $attachment);
            Log::info("  url==".$uploadDir . $splInfo->getSaveName());
           
            $source = ROOT_PATH . 'public'.$uploadDir.$splInfo->getSaveName();
            $dst_img = ROOT_PATH . 'public'.'/uploads/head/'.$splInfo->getSaveName();
            //$source =  '123.png';//原图片名称
            //$dst_img = 'text.png';//压缩后图片的名称
            $percent = 1;  #原图压缩，不缩放，但体积大大降低

            Log::info('src file =='.$source);
            Log::info('dest file =='.$dst_img);

            $image = (new imgcompress($source,$percent))->compressImg($dst_img);


            Log::info("**********************************************************************************upload  end ***************************************************************");
            $this->success(__('文件上传成功！'), [
                'url' => cdnurl('/uploads/head/'.$splInfo->getSaveName(),true)
            ]);
        } else {
            // 上传失败获取错误信息
            $this->error($file->getError());
        }
    }
     /**
     * 回答技术问题
     * 
     * @param title  标题
     * @param brand  品牌
     * @param specs  规格
     * @param type   类型
     * @param price  价格
     * @param trans_addr 交货地点
     * @param user_id 用户ID
     * @param req_contents 供求详情
     */
    public function answertechquestion()
    {
        Log::info("**********************************************************************************answertechquestion  start *************************************************************** ");
        $answer_to_user_id = $this->request->post("answer_to_user_id");//回答给于用户ID
        $answer_user_id    = $this->request->post("answer_user_id");   //回答用户ID
        $question_id       = $this->request->post("question_id");      //技术问题ID
        $answer_contents   = $this->request->post("answer_contents");      //回答的内容
        
        $answer_to_nickname = $this->request->post("answer_to_nickname");//回答给于用户名称
        $answer_nickname    = $this->request->post("answer_nickname");   //回答用户名称
        $answer_to_id       = empty( $this->request->post("answer_to_id")) ? '0' :  $this->request->post("answer_to_id");//技术问题ID

        Log::info("  answer_to_user_id==".$answer_to_user_id);
        Log::info("  answer_user_id==".$answer_user_id);
        Log::info("  question_id==".$question_id);
        Log::info("  answer_contents==".$answer_contents);
        Log::info("  answer_to_nickname==".$answer_to_nickname);
        Log::info("  answer_nickname==".$answer_nickname);
        Log::info("  answer_to_id==".$answer_to_id);

        //检查输入参数的合法信息
        if(empty($answer_user_id))
        {
            $this->error(__('回答用户ID不能为空'));
        }

        if(empty($question_id))
        {
            $this->error(__('技术问题ID不能为空'));
        }
        if(empty($answer_contents))
        {
            $this->error(__('回答的内容不能为空'));
        }
        if(empty($answer_to_nickname))
        {
            $this->error(__('回答给于用户名称不能为空'));
        }
        if(empty($answer_nickname))
        {
            $this->error(__('回答用户名称不能为空'));
        }


        //检查用户ID是否正确
        $userInfo = Db::query("select * from fa_user where id=:answer_user_id limit 1 ",['answer_user_id'=>$answer_user_id]);
        if(empty($userInfo))
        {
            $this->error(__('回答用户不存在'));
        }

        $tech_question = Db::query("select * from fa_litestore_tech_question where id=:question_id limit 1 ",['question_id'=>$question_id]);
        if(empty($tech_question))
        {
                    $this->error(__('技术问题ID在数据库中未找到记录'));
        }
        $as_num =$tech_question[0]['as_num'] ;

        if(empty($answer_to_user_id)){

            
            $answer_to_user_id =$tech_question[0]['user_id'] ;
            
        }
        else
        {
            $userInfo = Db::query("select * from fa_user where id=:answer_to_user_id limit 1 ",['answer_to_user_id'=>$answer_to_user_id]);
            if(empty($userInfo))
            {
                     $this->error(__('回答给于用户不存在'));
            }
        }
        $data = ['answer_to_user_id' => $answer_to_user_id,
                 'answer_user_id' => $answer_user_id,
                 'answer_to_user_name' => $answer_to_nickname,
                 'answer_user_name' => $answer_nickname,
                 'question_id' => $question_id,
                 'answer_to_id' => $answer_to_id,
                 'answer_contents' => $answer_contents,
                 'answer_time' => time(),
                 'createtime' => time(),
                 'updatetime' => time()
                ];
        
        $id= Db::name('litestore_tech_answer')->insertGetId($data);

        $updatedata['updatetime'] =time();
        $updatedata['as_num'] =$as_num+1;
        
        $res=Db::table('fa_litestore_tech_question')->where('id', $question_id)->update($updatedata);
        Log::info("**********************************************************************************answertechquestion  end *************************************************************** ");
        $this->success('插入成功', ['id'=>$id
                        
      ]);
    }


    
    public function findcity()
    {
        $lng =empty( $this->request->post("lng")) ? 115.01161 :  $this->request->post("lng");//技术问题ID
        $lat =empty( $this->request->post("lat")) ? 25.86076 :  $this->request->post("lat");//技术问题ID
        $lng_min = $lng-1;
        $lng_max = $lng+1;

        $lat_min = $lat-1;
        $lat_max = $lat+1;


        $citylist = Db::query("select mergename from fa_area where  lng > :lng_min AND lng < :lng_max  AND lat > :lat_min AND lat <:lat_max  limit 1 ",['lng_min'=>$lng_min,'lng_max'=>$lng_max,'lat_min'=>$lat_min,'lat_max'=>$lat_max]);
        if(empty($citylist))
        {
            $this->success(__('查询成功'), ['city'=>'江西/赣州市/赣县']);
        }
        $city =$citylist[0]['mergename'];
        $city = str_replace(',','/',$city);
        $city = str_replace('中国/','',$city);
        $this->success(__('查询成功'), ['city'=>'江西/赣州市/赣县']);

    }
    /**
     * 回答技术问题
     * 
     * @param title  标题
     * @param brand  品牌
     * @param specs  规格
     * @param type   类型
     * @param price  价格
     * @param trans_addr 交货地点
     * @param user_id 用户ID
     * @param req_contents 供求详情
     */
    public function techquestiondetail()
    {
        Log::info("**********************************************************************************techquestiondetail  start *************************************************************** ");
        $question_id =empty( $this->request->post("question_id")) ? '' :  $this->request->post("question_id");//技术问题ID

        Log::info("  question_id==".$question_id);


        //检查输入参数的合法信息
        if(empty($question_id))
        {
            $this->error(__('技术问题ID不能为空'));
        }
        $tech_question = Db::query("select a.id,a.user_id,b.nickname,b.mobile,b.avatar,a.qs_type,a.qs_images,a.qs_contents,a.as_num,a.qs_status,FROM_UNIXTIME(a.createtime, '%Y-%m-%d') as push_time from fa_litestore_tech_question a ,fa_user b where a.id=:question_id and a.user_id = b.id limit 1 ",['question_id'=>$question_id]);
        if(empty($tech_question))
        {
            $this->error(__('技术问题ID在数据库中未找到记录'));
        }
        $answer_to_user_id =$tech_question[0]['user_id'];
        if(empty($answer_to_user_id))
        {
            $this->error(__('技术问题user_id未找到记录'));
        }
        $iarr = $tech_question[0]['qs_images'] ;

        $images=explode(',',$iarr);
        $num = count($images);
        for($i=0;$i<$num;$i++){
            $images[$i]=cdnurl($images[$i],true);
        }
        $tech_question[0]['qs_images'] = $images;
        if(empty($tech_question[0]['avatar'])){$tech_question[0]['avatar']=cdnurl('/uploads/20200823/ph.png',true);}
        $sql="select a.id,b.nickname,b.avatar,a.answer_to_user_id,a.answer_user_id,a.question_id,a.answer_contents,FROM_UNIXTIME(a.answer_time, '%Y-%m-%d') as answer_time from  fa_litestore_tech_answer  a ,fa_user b where  a.answer_user_id = b.id and  question_id=:question_id and a.answer_to_id=:answer_to_id order by a.id   limit 30 ";
        $techquestiondetail=Db::query($sql,['question_id'=>$question_id,'answer_to_id'=>0]);
        $techquestiondetail2=[];
        foreach($techquestiondetail as $index =>$item)
        {
            $answer_user_id = $item['answer_user_id'];
            $answer_to_id = $item['id'];
            $subdetail= Db::query("select a.id,b.nickname,b.avatar,a.answer_to_user_id,a.answer_to_user_name,a.answer_user_id,a.answer_user_name,a.question_id,a.answer_contents,FROM_UNIXTIME(a.answer_time, '%Y-%m-%d') as answer_time from  fa_litestore_tech_answer  a,fa_user b  where  a.answer_user_id = b.id and question_id=:question_id and answer_to_user_id=:answer_to_user_id and a.answer_to_id=:answer_to_id order by a.id   limit 30 ",['question_id'=>$question_id,'answer_to_user_id'=>$answer_user_id,'answer_to_id'=>$answer_to_id]);
            $subdetail2=[];
            foreach($subdetail as $index =>$item2)
            {
                $subdetail2[] = [
                'answer_to_user_id'=>$item2['answer_to_user_id'],
                'answer_user_id'=>$item2['answer_user_id'],
                'answer_to_nickname'=>$item2['answer_to_user_name'],
                'answer_nickname'=>$item2['answer_user_name'],                
                'question_id'=>$item2['question_id'],
                'answer_to_id'=>$item['id'],
                'answer_contents'=>$item2['answer_contents'],
                'answer_time'=>$item2['answer_time']];
            }

            if(empty($item['avatar'])){$item['avatar']='/uploads/20200823/ph.png';}
            $techquestiondetail2[] = ['id'=>$item['id'],
                                       'nickname'=>$item['nickname'],
                                       'avatar'=>cdnurl($item['avatar'],true),
                                       'answer_to_user_id'=>$item['answer_to_user_id'],
                                       'answer_user_id'=>$item['answer_user_id'],
                                       'question_id'=>$item['question_id'],
                                       'answer_contents'=>$item['answer_contents'],
                                       'answer_time'=>$item['answer_time'],
                                       'subdetail'=>$subdetail2];
            
        }
        Log::info("**********************************************************************************techquestiondetail  end *************************************************************** ");
        $data = ['question' =>$tech_question[0],
            'techanswerdetail'=>$techquestiondetail2];
        $this->success(__('查询成功'), $data);
    }

    /**
     * 获取服务订单类型列表
     * @param  void
     * @return serviceorderlist
     */
    public function serviceorderlist()
    {
        Log::info("**********************************************************************************serviceorderlist  start *************************************************************** ");

        $litestoreServiceOrderType = new LitestoreServiceOrderType();
        $servicetypelist = $litestoreServiceOrderType->select();

        foreach ($servicetypelist as $index => $item) {
            $servicetypelist[$index] = ['desc_image' => cdnurl($item['desc_image'], true),
             'id'=> $item['id'],
            'name' =>$item['name'],
            'price' =>intval($item['price'].''),
            'desc' =>$item['desc'],
            ];
        }
        Log::info($servicetypelist);
        Log::info("**********************************************************************************serviceorderlist  end *************************************************************** ");
        $this->success('获取成功', [
                        'servicetypelist' => $servicetypelist
      ]);
    }

    /**
     * 名片模板信息列表
     * 
     * @param  void
     * @return cardtpllist
     */
    public function cardtpllist()
    {
        Log::info("**********************************************************************************cardtpllist  start *************************************************************** ");
        $litestoreCardTpl = new LitestoreCardTpl();
        $servicetypelist = $litestoreCardTpl->select();

        foreach ($servicetypelist as $index => $item) {
            $servicetypelist[$index] = ['tpl_image' => cdnurl($item['tpl_image'], true),
             'id'=> $item['id'],
            'name' =>$item['name'],
            'desc' =>$item['name'],
            'style'=>json_decode($item['desc'],TRUE)
            ];
        }
        Log::info("**********************************************************************************cardtpllist  end *************************************************************** ");        
        $this->success('获取成功', ['servicetypelist' => $servicetypelist]);
    }

    /**
     * 更新用户的默认模板
     * 
     * @param  void
     * @return true
     */
    public function updatecardtpl()
    {
        Log::info("**********************************************************************************updatecardtpl  start *************************************************************** ");        
        $user_id     =empty( $this->request->post("user_id")) ? '' :  $this->request->post("user_id");//技术问题ID
        $card_tpl_id =empty( $this->request->post("card_tpl_id")) ? '' :  $this->request->post("card_tpl_id");//技术问题ID


        Log::info("  user_id==".$user_id);
        Log::info("  card_tpl_id==".$card_tpl_id);



        $servicetypelist= Db::name('litestore_card_tpl')->where(['id'=> $card_tpl_id])->limit(1)->select();

        if(empty($servicetypelist))
        {
            $this->error("名片模板ID在数据库中没有记录！");
        }
        
        if (empty($user_id)) {
            $this->error("用户ID不能为空");
        }
        if (empty($card_tpl_id)) {
            $this->error("名片模板ID不能为空");
        }else
        {
            $updatedata['card_tpl_id'] =$card_tpl_id;
            $updatedata['card_tpl_image'] =$servicetypelist[0]['tpl_image'];
        }
        $updatedata['updatetime'] =time();
        $res=Db::table('fa_user')->where('id', $user_id)->update($updatedata);
        Log::info("**********************************************************************************updatecardtpl  end *************************************************************** ");        
        $this->success('更新成功', ['res' => $res]);
    }
    

    


     /**
     * 更新技术问题处理状态
     * 
     * @param  void
     * @return true
     */
    public function updatetechquestionstatus()
    {
        Log::info("**********************************************************************************updatetechquestionstatus  start *************************************************************** ");        
        $question_id     =empty( $this->request->post("question_id")) ? '' :  $this->request->post("question_id");//技术问题ID
     
        Log::info("  question_id==".$question_id);


        if (empty($question_id)) {
            $this->error("问题ID不能为空");
        }else
        {
            $updatedata['updatetime'] =time();
            $updatedata['qs_status'] ='1';
        }
        
        $res=Db::table('fa_litestore_tech_question')->where('id', $question_id)->update($updatedata);
        Log::info("**********************************************************************************updatetechquestionstatus  end *************************************************************** ");        
        $this->success('更新成功', ['res' => $res]);
    }

   /**
     * 名片模板信息列表
     * 
     * @param  void
     * @return cardtpllist
     */
    protected function getdefaultcardtplimage()
    {
        Log::info("**********************************************************************************getdefaultcardtplimage  start *************************************************************** ");        
        $litestoreCardTpl = new LitestoreCardTpl();
        $cardtpllist = $litestoreCardTpl->limit(1)->select();
        if(empty($cardtpllist))
        {
            return '';
        }
        else{
            return $cardtpllist[0]['tpl_image'];
        }

        return '';
    }
    function saveheadimgurl($user_id,$headimg){

        if(empty($headimg)){
        $url='https://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTJZRibSeBp0DFA1jT0iaTn4TNicRaPhVcWiaIn7a56nSeVicNdic8TLwOdhB6pBFfVtoSySuryYGFn2JAzA/132';
        }else{
            $url=$headimg;
        }
        
        $img_file = file_get_contents($url);  
        $img_content= base64_encode($img_file); 
        $type = 'jpeg';//得到图片类型png?jpg?gif? $new_file = "./cs/cs.{$type}"; 
        $headimgpath = ROOT_PATH . 'public'.'/uploads/head/'.$user_id.'.jpg';
        if (file_put_contents($headimgpath, base64_decode($img_content)))
        {  
           return  '/uploads/head/'.$user_id.'.jpg';
        }
        else{
            return "";
        }  
    
    }
    /**
     * 获取手机号码
     */
    public function get_PhoneNum(){
        Log::info("**********************************************************************************get_PhoneNum  start *************************************************************** ");        
        $encryptedData = $this->request->post("encryptedData");
        $iv = $this->request->post("iv");
        $user_id = $this->request->post("user_id");

        Log::info("  encryptedData==".$encryptedData);
        Log::info("  iv==".$iv);
        Log::info("  user_id==".$user_id);

        //检查输入参数的合法信息
        if(empty($encryptedData))
        {
            $this->error(__('encryptedData不能为空'));
        }
        //检查输入参数的合法信息
        if(empty($iv))
        {
            $this->error(__('iv不能为空'));
        }
        //检查输入参数的合法信息
        if(empty($user_id))
        {
            $this->error(__('UserId不能为空'));
        }

        $third = Third::where(['user_id' => $user_id, 'platform' => 'wxapp'])->find();
        $sessionKey = $third['access_token'];
        $config = get_addon_config('litestore');
        $options = [
                    //'debug'  => true,
                    'mini_program' => [
                        'app_id'   => $config['AppID'],
                        'secret'   => $config['AppSecret'],
                        'token'    => 'component-token',
                        'aes_key'  => 'component-aes-key'
                        ],
                    ];
        $app = new Application($options);
        $this->miniProgram = $app->mini_program;
        $aaa=$this->miniProgram->encryptor->decryptData($sessionKey, $iv, $encryptedData);
        Log::info("**********************************************************************************get_PhoneNum  end *************************************************************** ");        
        $this->success('',$aaa );
    }    
    
    /**
     * 批量造数据
     */
    public function createdata(){
        $type = $this->request->post('type');

        //企业数据
        if($type ==='1')
        {
                $compname = array(
                    "綦雪珍","义灵慧","表寄文","佴白竹","唐杏儿","叶雁芙","溥静芙","赛稷","申小翠","巢妍","陆鸿远","衅博瀚","竺雅媚","己晓兰","狂寄风","南宫依美","宰桐欣","山暄嫣",
                    "颜子璇","旅家馨","青慧云","冠傲柔","悉展","铎凌柏","登俊喆","鲜林","雷曼云","烟元德","步寻冬","濮宜民","绍问玉","阮鸿卓","诸访烟","曾牧歌","区从云","功滢","典聪睿",
                    "汗代巧","腾芮波","申屠祺祥","万俟思菱","蒯家欣","摩航","铁孤兰","严采蓝","剧寒香","恭安澜","亓官晓骞","邝薇","雀从冬","箕慈","兴夜梅","吉秋白","竹初蝶","段干思","洁强山",
                    "灵野沛","哀慧心","敛涵菱","介和","洽长孙","子默官","优乐辟","逸春么","甫宇文","云水全","秀媚兆","悠奕光","东向凌","波公良","谧千和","畅折蕴","藉业翠","皋涵涤","栾语山",
                    "东方兰","梦单翊","君百里","一璇辜","半雪少","静珊随","琼英萧","念雁养","雁卉单","于智纯","赫连昂","杰茂志","行问俊","楠伊飞","昂殳姣","丽明寻","雪马佳","静和佛","恬静藤",
                    "志用旗","香春符","青烟琦","怜姚采","文粘子","瑜巴乐","心赧浩","实芮","欢路元","勋奕奇","志蔺欣","畅斛嘉","懿香","娟娟","亢亦梅","蚁问寒","慕佳美","赖荏英","浩浩兴","远悦满",
                    "春英称","君浩磨","涵煦米","英耀翠","晨希国","良骏寒","元龙侍","震尉迟","倚云尧","丹翠卓","力夫钊","华栋彤","霞兰从","冬独韵","诗果骊","蓉藏晏","然闻人","倩美开","咸翁辰",
                    "锟绪傲","易宣昆","宇王雅","达钦从","筠庄旻","京庸聊","敏学伯","访冬宗","维运节","恨桃由","乐山鲁","儒镇诗","蕊虞天","真悟雁","桃褚慧","云仙宏","富勤德","宇理乐","家碧鲁","玉珂白",
                    "和美逄","小凝艾","靖易威","尔槐纳","喇格菲","狂尔容","摩尔冬","逢侬速","水彤苑","寻桃洪","夏柳可","辰碧艳","芳示鸿","风始妮","利璠瑜","从睿姿","汪令美","富察志","专于智","敏邝梦",
                    "宦怜云","出访文","买鸿才","祁念文","濮阳芳","泽候荷","是安青","第五新","翰薄傲","柏仲佳","惠郭诗","槐霍春","姝唐香","桃念从","霜拜庄","雅孔刚","洁沃敏","才佼傲","之衣建","元家歆",
                    "美毕致","萱泷暄","美恭小","凝范","姜骊霞","赛平惠","乐梦槐",
                    "秀英溥","振梅摩","秀梅狂","兰波玉","枝萧其","英丑树","花班遐","思謇萱","说永修","杭孝房","桂花所","菲师淑","英祭玉","花言素","兰僧杨","氏妫爱","景考恕","倪玉枝","玉蓉那","增岳粟",
                    "贤旗清","安和秀","英骑墨","彻鄢伦","纪玉花","娄若谷","户培胜","苌元修","焉晚  ","竹齐  ","永芬  ","益霞漆","兴召秋","芹泷玉","芬步秀","荣李雪","谌桂兰","曲新兰","是桂花","士玉英",
                    "裔染谢","竹青礼","广英万","诚九玉","兰爱淑","琴稽蕾","银亮温","振华肖","玉巧骆","礼性素","花罕松","兰允运","旺朱时","芳真秀","珍蹉秀","荣郏奕","琛慎秋","英夷义","藩绿柳","尉夕泰",
                    "汀兰司","恭羿富","贵包恒","竹伊遐","思充淑","珍桓翠","花岳玉","英符永","修示萱","冯汀兰","蛮秀荣","戎雪那","长顺溥","菊桐玉","枝贸秀","荣佴绿","柳瞿玉","花濯恕","有奕琛","荤良姬",
                    "桂花华","宏法罗","洁乘元","斐系微","兰师霞","柏桂花","苌增岳","天春尤","同书过","建设蓟","松兰章","宁莱义","郜金兰","闾墨彻","北学岺","苦芙伦","长征亓","玉兰平","若谷己","素芹弭",);
                    
                for ($i=0; $i < count($compname); $i++) {
                    
                    $group_id ='7';
                    if($i>=0 && $i<50)
                    {
                        $group_id ='2';    
                    }
                    if($i>=50 && $i<100)
                    {
                        $group_id ='3';    
                    }
                    if($i>=100 && $i<150)
                    {
                        $group_id ='4';    
                    }
                    if($i>=150 && $i<180)
                    {
                        $group_id ='5';    
                    }
                    if($i>=180 && $i<200)
                    {
                        $group_id ='6';    
                    }
                    if($i>=200 && $i<300)
                    {
                        $group_id ='7';    
                    }
                    
                    $data = ['nickname' => $compname[$i], 
                            'username' => 'test'.$i, 
                            'group_id' =>  $group_id, 
                            'email' => 'test'.$i.'@qq.com', 
                            'mobile' => '18870749166', 
                            'avatar'=>'/assets/img/avatar.png',
                            'level'=>'1',
                            'password'=>'04eb6add6c505161ea24f50462d5ca0e',
                            'gender'=>'0',
                            'businesslicense_images'=>'/uploads/20200920/yyzz.jpg',
                            'createtime'=>time(),
                            'jointime'=>time(),
                            'updatetime'=>time(),
                            'status'=>'normal',
                            'region_city'=>'江西省/赣州市/赣县区',
                            'address'=>'城南大道梅林古镇104号',
                            'work'=>'机制炭生产',
                            'experience'=>'20年的生产工作',
                            'companyname'=>$compname[$i].'科技技术有限责任公司',
                            'businessscope'=>'机制炭生产和销售',
                            'companyprofile'=>'在这个行业摸爬滚打20年的机制炭生产和销售',
                            'card_tpl_id'=>'1',
                            'card_tpl_image'=>'/uploads/20200920/249d96e7918477d503cc4f9c9790f507.jpg',
                            'certify_status'=>'1',
                            'appr_status'=>'1'];
                            $id= Db::name('user')->insertGetId($data);
            }
        }
         //供求信息
         else if($type ==='2')
         {
            $title = array("海亦",
            "初晴",
            "巧蕊",
            "听安",
            "芷雪",
            "以松",
            "梦槐",
            "寒梅",
            "香岚",
            "寄柔",
            "映冬",
            "孤容",
            "晓蕾",
            "安萱",
            "听枫",
            "夜绿",
            "雪莲",
            "从丹",
            "碧蓉",
            "绮琴",
            "雨文",
            "幼荷",
            "青柏",
            "痴凝",
            "初蓝",
            "忆安",
            "盼晴",
            "寻冬",
            "雪珊梦",
            "寒迎南",
            "香采南",
            "如彤春",
            "竹采枫",
            "若雁翠",
            "阳沛容",
            "幻翠山",
            "兰芷波",
            "雪瑶代",
            "巧寄云",
            "慕卉冷",
            "松涵梅",
            "书白乐",
            "天雁卉",
            "宛秋傲",
            "旋新之",
            "凡儿夏",
            "真静枫",
            "痴柏恨",
            "蕊乐双",
            "忆雪友",
            "卉幻翠",
            "靖柔寻",
            "菱丹翠",
            "安阳雅",
            "寒惜筠",
            "尔安雁",
            "易飞瑶",
            "夏兰沛",
            "蓝静丹",
            "山芙笑",
            "晴新烟",
            "笑旋",
            "雁兰凌",
            "翠秋莲",
            "书桃傲",
            "语儿映",
            "菡初曼",
            "听云孤",
            "松初夏",
            "雅香语",
            "雪初珍",
            "白安冰",
            "薇诗槐",
            "冷玉冰",
            "巧之槐",
            "香柳问",
            "春夏寒",
            "半香诗",
            "筠新梅",
            "白曼安",
            "波从阳",
            "含桃曼",
            "卉笑萍",
            "碧巧晓",
            "露寻菡",
            "沛白平",
            "灵水彤",
            "安彤涵",
            "易乐巧",
            "白玉问",
            "玉寄松",
            "丹蝶元",
            "瑶冰蝶",
            "访曼代",
            "灵芷烟",
            "白易尔",
            "阳怜烟",
            "平卉丹",
            "寒访梦",
            "绿凝冰",
            "菱语蕊",
            "痴梅思",
            "烟忆枫",
            "映菱访",
            "儿凌兰",
            "曼岚若",
            "枫傲薇",
            "凡灵乐",
            "蕊秋灵",
            "谷槐觅",
            "云水凡",
            "灵秋代",
            "卉笑天",
            "白夏又",
            "青冬梅",
            "从珊又",
            "香雪容",
            "彤冷",
            "萱夜",
            "卉念",
            "雁尔",
            "阳水荷",
            "尔真孤",
            "阳之卉",
            "依薇妙",
            "双醉巧",
            "痴海惜",
            "筠从筠",
            "碧白曼",
            "珍觅晴",
            "寄蓉慕",
            "雁水丹",
            "幼霜凝",
            "又松丹",
            "元旋怜",
            "云觅丹",
            "槐水冬",
            "天青语",
            "丝怀芹",
            "彤雪绿",
            "冬凌春",
            "凌寒代",
            "幼白山"
             );

            for ($i=0; $i < count($title); $i++) {
           
              
                $data = ['title' =>'供应品牌'.$title[$i].'的机制炭', 
                'brand' => $title[$i].'机制炭', 
                'specs' =>  '1000x100', 
                'type' => '1', 
                'info_type' => '1', 
                'price'=>'2000万',
                'trans_addr'=>'江西省赣州市赣县区梅林古镇104号',
                'req_contents'=>'我公司需要供应100吨的机制进行销售',
                'num'=>'100吨',
                'detail_images'=>'/uploads/20200926/bf234f63a579a7aa851b8067ecebfe3b.jpg,/uploads/20200926/e4d243638845133e2e50a532c4f2fc01.jpg,/uploads/20200926/553cc39f170c38f6d7f1913f1cb157ab.jpg,/uploads/20200926/30f1d88ad07a1ca9c19b27ee2020ff88.jpg',
                'publish_time'=>time(),
                'user_id'=>'25',
                'updatetime'=>time(),
                'createtime'=>time(),
                ];

            $id= Db::name('litestore_request')->insertGetId($data);
        }
        }
        else if($type ==='3')
        {
            $now = date('Y-m-d',time());
            $oneyear =  date("Y-m-d",strtotime("-1days",strtotime("+1years",strtotime(date('Y-m-d H:i:s',time())))));
        } 
        else if($type==='4')
        {
            $source = ROOT_PATH . 'public'.'/uploads/head/'.'fcdb35a6b9cf9cc1c003f52a2fa9afa6.png';
            $dst_img = ROOT_PATH . 'public'.'/uploads/head/'.'433.jpg';
            //$source =  '123.png';//原图片名称
            //$dst_img = 'text.png';//压缩后图片的名称
            $percent = 0.5;  #原图压缩，不缩放，但体积大大降低
            $image = (new imgcompress($source,$percent))->compressImg($dst_img);
        }
        $this->success('', []);
    }
    
   
}
